package in.muton.edushare.components.tasks.electives.allotment;

import in.muton.edushare.processing.objects.CourseDataHandler;
import in.muton.edushare.wicket.models.CayenneList;
import in.muton.edushare.wicket.models.CayenneModel;

import java.util.List;

import org.apache.wicket.model.IModel;

import com.edushare.common.dao.BatchDAO;
import com.edushare.common.dao.CourseInstancesDAO;
import com.edushare.common.dao.CurriculumDAO;
import com.edushare.common.dao.EnrolmentsDAO;
import com.edushare.common.orm.ORMInterface;
import com.edushare.common.vo.Batches;
import com.edushare.common.vo.CourseInstances;
import com.edushare.common.vo.Courses;
import com.edushare.common.vo.Universities;
import com.edushare.common.vo.Users;

public class MandatoryCourseAllot {

	public MandatoryCourseAllot(IModel<Universities> univModel) {
		this.univModel = univModel;
	}

	public void allocateCoursesSem(ORMInterface orm) {
		BatchDAO bDAO = new BatchDAO(orm);
		List<Batches> batchList = bDAO.getAllBatches(univModel.getObject());
		for (Batches b : batchList) {
			bDAO.endSemester(b);
			if(b.getBatchStatus() != Batches.BATCH_GRADUATED)
				allocateCoursesSem(b, orm);
		}
	}

	public void allocateCoursesSem(Batches b, ORMInterface orm) {
		CurriculumDAO cDAO = new CurriculumDAO(orm);
		CourseInstancesDAO instDAO = new CourseInstancesDAO(orm);
		EnrolmentsDAO eDAO = new EnrolmentsDAO(orm);
		BatchDAO bDAO = new BatchDAO(orm);
		List<Courses> courseList = cDAO.getMandatoryCourses(b.getCurricula(), b
				.getCurrentSemester());

		for (Courses c : courseList) {
			CourseInstances cInst = instDAO.getActiveInst(c); 
			if(cInst == null){
				cInst = instDAO.newBatchInst(c);
			}
			eDAO.enrolTeachers(cInst, getPrevInstTeachers(c));
			eDAO.enrolStudents(cInst, bDAO.getUsers(b));
		}
	}

	public static List<Users> getPrevInstTeachers(Courses course) {
		List<CourseInstances> cInst = course.getCourseInstances();
		CayenneList<Users> teacherList = new CayenneList<Users>(null);
		for (CourseInstances c : cInst) {
			teacherList.add(new CourseDataHandler(new CayenneModel<CourseInstances>(c))
					.getTeachers());
		}
		return teacherList.getUtilList();
	}

	private IModel<Universities> univModel;

}
